import { useState } from 'react';
import { uploader } from '../api/upload';
import { Toast } from '@douyinfe/semi-ui';

/**
 * 图片编辑专用的上传 Hook
 * @param {Object} options - 配置选项
 * @param {Function} options.onSuccess - 上传成功回调
 * @param {Function} options.onError - 上传失败回调
 * @returns {Object} - 返回上传相关的状态和方法
 */
export const useImageUpload = (options = {}) => {
    const { onSuccess, onError } = options;
    
    const [uploading, setUploading] = useState(false);
    const [progress, setProgress] = useState(0);
    const [uploadedFile, setUploadedFile] = useState(null);
    
    /**
     * 上传图片文件
     * @param {File} file - 要上传的文件
     * @param {string} fileName - 自定义文件名（可选）
     * @returns {Promise<Object>} - 上传结果
     */
    const handleUpload = async (file, fileName) => {
        if (!file) {
            const error = new Error('请选择要上传的文件');
            onError?.(error);
            Toast.error('请选择要上传的文件');
            return { success: false, error };
        }
        
        setUploading(true);
        setProgress(0);
        
        try {
            // 模拟上传进度
            const progressInterval = setInterval(() => {
                setProgress(prev => {
                    if (prev >= 90) {
                        clearInterval(progressInterval);
                        return 90;
                    }
                    return prev + 10;
                });
            }, 100);
            
            // 执行上传
            const result = await uploader(file, fileName);
            
            clearInterval(progressInterval);
            setProgress(100);
            
            if (result.success) {
                setUploadedFile({
                    file,
                    url: result.url,
                    fileName: result.fileName
                });
                
                onSuccess?.(result);
                Toast.success('图片上传成功');
                
                return result;
            } else {
                throw new Error('上传失败');
            }
            
        } catch (error) {
            console.error('图片上传失败:', error);
            
            onError?.(error);
            Toast.error(error.message || '图片上传失败');
            
            return { success: false, error };
            
        } finally {
            setUploading(false);
            // 延迟重置进度条
            setTimeout(() => {
                setProgress(0);
            }, 1000);
        }
    };
    
    /**
     * 重置上传状态
     */
    const resetUpload = () => {
        setUploading(false);
        setProgress(0);
        setUploadedFile(null);
    };
    
    /**
     * 验证文件是否符合要求
     * @param {File} file - 要验证的文件
     * @param {Array} allowedTypes - 允许的文件类型数组
     * @returns {Promise<boolean>} - 验证结果
     */
    const validateFile = async (file) => {
        // 验证图片尺寸和宽高比
        const actualFile = file.fileInstance || file;
        const isValidDimensions = await validateImageDimensions(actualFile);
        if (!isValidDimensions) {
            return false;
        }
        return true;
    };
    
    /**
     * 验证图片尺寸和宽高比
     * @param {File} file - 图片文件
     * @returns {Promise<boolean>} - 验证结果
     */
    const validateImageDimensions = (file) => {
        return new Promise((resolve) => {
            const img = new Image();
            const url = URL.createObjectURL(file);
            
            img.onload = () => {
                URL.revokeObjectURL(url);
                
                const { width, height } = img;
                
                // 检查尺寸范围：不小于300px，不大于6000px
                if (width < 300 || height < 300) {
                    Toast.error('图片宽度和高度不能小于300px');
                    resolve(false);
                    return;
                }
                
                if (width > 6000 || height > 6000) {
                    Toast.error('图片宽度和高度不能大于6000px');
                    resolve(false);
                    return;
                }
                
                // 检查宽高比：1:2.5 ~ 2.5:1
                const aspectRatio = width / height;
                const minRatio = 1 / 2.5; // 0.4
                const maxRatio = 2.5 / 1;  // 2.5
                
                if (aspectRatio < minRatio || aspectRatio > maxRatio) {
                    Toast.error('图片宽高比必须在1:2.5到2.5:1之间');
                    resolve(false);
                    return;
                }
                
                resolve(true);
            };
            
            img.onerror = () => {
                URL.revokeObjectURL(url);
                Toast.error('无法读取图片信息');
                resolve(false);
            };
            
            img.src = url;
        });
    };
    
    return {
        // 状态
        uploading,
        progress,
        uploadedFile,
        
        // 方法
        handleUpload,
        resetUpload,
        validateFile
    };
};

export default useImageUpload;